package com.yonyou.jrmob.lryapp.login;

import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.hss01248.dialog.StyledDialog;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.yonyou.jr.mob.rzkh.R;
import com.yonyou.jrmob.lryapp.MainActivity;
import com.yonyou.uap.emm.http.HttpCallback;
import com.yonyou.uap.emm.service.IUAPEMMService;
import com.yonyou.uap.emm.util.EmmUtil;
import com.yonyou.uap.emm.util.EnterpriseMobileManager;
import com.yonyou.uap.emm.util.deviceAdminReceiver;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import jrmob.yonyou.com.commonlib.app_config_tool.constant.Constant;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.LogUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.StatusBarUtil;
import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;
import jrmob.yonyou.com.commonlib.baseui.base.BaseApp_lib;

public class LoadingActivity extends BaseActivityMob_lib {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading);

        StatusBarUtil.StatusBarLightMode(this);
        StatusBarUtil.setStatusBarColor(this,R.color.white);

       /* if (readLocationValue("isLoginEmm").equals("true")){

            Handler handler = new Handler(getMainLooper());
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity(new Intent(LoadingActivity.this, LoginActivity.class));
                    finish();
                }
            }, 1000);
        }else {
            loginEmm();
        }*/

        Handler handler = new Handler(getMainLooper());
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                startActivity(new Intent(LoadingActivity.this, LoginActivity.class));
                finish();
            }
        }, 1000);




    }

    @Override
    public void initView() {

    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {

    }


    /*********** 登录 emm start *********/

    public static final String HTTP_emm = "http"; // emm 注册协议
    public static final int LOGIN_EMM_FAILED = 5980;  // 失败标识
    public static final int LOGIN_EMM_SUCCESS = 5880;  // 成功标识

    /**
     * 注册,登录emm
     */
    void loginEmm() {

        Map map = BaseApp_lib.getMap_app();
        map.put("emm_ip", Constant.emmIP);
        map.put("emm_port", Constant.emmPORT);
        final String IP_emm =Constant.emmIP;
        final String PORT_emm = Constant.emmPORT;


        if (IP_emm.length() <= 7 || TextUtils.isEmpty(PORT_emm)) {
            showMessage("emm 配置有误,请检查!");
            return;
        }

        // emm 登录注册
        final EnterpriseMobileManager enterpriseMobileManager = new EnterpriseMobileManager(
                this, IP_emm, PORT_emm, HTTP_emm);
        new Thread(new Runnable() {
            @Override
            public void run() {
                regist(IP_emm, PORT_emm, Constant.emmUserName, Constant.emmPWD, null, enterpriseMobileManager);
            }
        }).start();


    }


    /**
     * handler
     */
    android.os.Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOGIN_EMM_FAILED:  // emm 报错
                    showMessage(msg.obj);
                    break;
                case LOGIN_EMM_SUCCESS:  // emm 成功 (比如跳转到主界面)
                    writeLocationFile("isLoginEmm","true");
                    intentToMainPageActivity();
                    break;
                default:
                    break;
            }
        }
    };



    /******************  emm deviceadmin start *******************************/

    boolean isOpenDevice = true;//设备管理器激活标示

    public void openAdmin(ComponentName mDeviceAdminSample, Activity activity, int requestCode) {
        DevicePolicyManager mDPM = (DevicePolicyManager) activity.getSystemService(Context.DEVICE_POLICY_SERVICE);
        boolean active = mDPM.isAdminActive(mDeviceAdminSample);
        if (!active) {
            if (isOpenDevice) {
                isOpenDevice = false;
                Intent intent = new Intent("android.app.action.ADD_DEVICE_ADMIN");
                intent.putExtra("android.app.extra.DEVICE_ADMIN", mDeviceAdminSample);
                intent.putExtra("android.app.extra.ADD_EXPLANATION", "说明: 此应用只针对移动工作台管控.");
                activity.startActivityForResult(intent, requestCode);
            } else {
                handler.sendEmptyMessage(LOGIN_EMM_SUCCESS);  //执行登陆
            }
        } else {
            handler.sendEmptyMessage(LOGIN_EMM_SUCCESS);  //执行登陆
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 121) {
            handler.sendEmptyMessage(LOGIN_EMM_SUCCESS);  //执行登陆
        }

    }

    /**
     * emm 登录成功后调用
     *
     */
    public void openEmm(Context context, String host, String port, String emmusercode, String emmpwd) {
        EnterpriseMobileManager.startCommandServices(context, 5);
        ComponentName mDeviceComponentName = null;
        SharedPreferences sp = context.getSharedPreferences("UAPHomeConfigure", Context.MODE_PRIVATE);
        //MA
        sp.edit().putString("host", host).commit();
        sp.edit().putString("port", port).commit();

        //Emm
        sp.edit().putString(EmmUtil.EMMHOST, host).commit();
        sp.edit().putString(EmmUtil.EMMPORT, port).commit();


        sp.edit().putString("emmusercode", emmusercode).commit();
        sp.edit().putString("emmpwd", emmpwd).commit();


        EnterpriseMobileManager enterpriseMobileManager1 = new EnterpriseMobileManager(context, host, port);
        if (EmmUtil.isOpenEMM) {
            LogUtils.e("yyyBootReceiver - Emm is open");
            //EnterpriseMobileManager enterpriseMobileManager = new EnterpriseMobileManager(context,host , port);
            if (mDeviceComponentName == null)
                mDeviceComponentName = new ComponentName(context,
                        deviceAdminReceiver.class);

//            enterpriseMobileManager1.startStrategy(mDeviceComponentName, 2);
//            EnterpriseMobileManager.openAdmin();
            IUAPEMMService.url = EmmUtil.getEmmHost(context) + "/mobem/push/strategy";
            IUAPEMMService.mDeviceComponentName = mDeviceComponentName;
//            Intent Service = new Intent();
//            Service.setAction("android.intent.action.IUAPEMMService");
//            Service.setPackage(context.getPackageName());
            context.startService(new Intent(context, IUAPEMMService.class));

            // 是否强制性打开设备管理器
//            EnterpriseMobileManager.openAdmin(mDeviceComponentName, mActivity, 121);
            openAdmin(mDeviceComponentName, mActivity, 121);

            Intent startServiceIntent = new Intent();
            startServiceIntent.setAction("android.intent.action.IUAPWatchService");
            startServiceIntent.setPackage(context.getPackageName());
            context.startService(startServiceIntent);

            enterpriseMobileManager1.startGroupService(3);
        } else {
            LogUtils.e("yyyBootReceiver - Emm关闭");
            handler.sendEmptyMessage(LOGIN_EMM_SUCCESS);  //执行登陆
        }
    }


    /**********************  emm deviceadmin end  ***************************/


    private void intentToMainPageActivity() {
        Intent intent = new Intent();
        intent.setClass(LoadingActivity.this,LoginActivity.class);
        startActivity(intent);
        finish();
    }

    //注册EMM
    private void regist(final String host, final String port, final String user, final String passwd,
                        final String enterpriseID, EnterpriseMobileManager enterpriseMobileManager) {
        try {
            enterpriseMobileManager.registerUser(user, passwd, enterpriseID,
                    new HttpCallback() {

                        @Override
                        public void execute(String arg0) {

                            //标记
                            if (TextUtils.isEmpty(arg0)) {
                                LogUtils.e("EMM登录有误! " + arg0);
                                Message message = new Message();
                                message.obj = arg0;
                                message.what = LOGIN_EMM_FAILED;
                                handler.sendMessage(message);
                                return;
                            }
                            try {
                                final JSONObject jsonObject = new JSONObject(arg0);
                                String code = jsonObject.getJSONObject("data").getString("code");
                                // 注册成功
                                if ("1".equals(code)) {
                                    Message message = new Message();
                                    message.what = LOGIN_EMM_SUCCESS;
                                    handler.sendMessage(message);

                                    //启动emm 监控service
//                                    openEmm(mActivity, host, port, user, passwd);

                                } else if ("0".equals(code)) {
                                    String status = jsonObject.getJSONObject("data").getString("status");
                                    String msg = jsonObject.getJSONObject("data").optString("msg", "");
                                    if (status.equals("0")) {

                                        if (mActivity != null) {
                                            LogUtils.e("EMM登录有误! " + arg0);
                                            Message message = new Message();
                                            message.obj = arg0;
                                            message.what = LOGIN_EMM_FAILED;
                                            handler.sendMessage(message);
                                        }

                                    } else if (status.equals("4")) {

                                        //android 7.0
                                        writeLocationFile(EmmUtil.EMMUSER, "");

                                        if (mActivity != null) {
                                            Message message = new Message();
                                            message.obj = arg0;
                                            message.what = LOGIN_EMM_FAILED;
                                            handler.sendMessage(message);
                                        }
                                    }
                                }
                            } catch (JSONException e) {
                                LogUtils.e(e);
                                e.printStackTrace();
                            }
                        }
                    });
        } catch (Exception e) {
            LogUtils.e(e);
            e.printStackTrace();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
/*********** 登录 emm end *********/

}
